#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
    flag = true;//服务器停止
    server = new QTcpServer(this);
}

Widget::~Widget()
{
    delete ui;
}

void Widget::on_pushButton_clicked()
{
    if(flag)
    {
        flag = false;
        ui->pushButton->setText("stop");
        //启动服务器
        server->listen(QHostAddress::Any,8888);
        connect(server,SIGNAL(newConnection()),this,SLOT(newCnd()));
    }
    else{
        flag = true;
        ui->pushButton->setText("Start");
        server->close();
        socket->close();
    }
}
void Widget::newCnd(){
    qDebug()<<"cnd";
    while(server->hasPendingConnections())
    {
     socket = server->nextPendingConnection();
     connect(socket,SIGNAL(readyRead()),this,SLOT(recv_data()));

    }

}
void Widget::recv_data(){
    QByteArray data = socket->readAll();//读客户端数据
//    socket->write(data);
    ui->textEdit->setPlainText(data);

}

void Widget::on_pushButton_2_clicked()
{
    QString msg = ui->lineEdit->text();
    socket->write(msg.toLatin1());
}
